package initialize

import (
	"blog-server/global"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"os"
	"time"
	"xorm.io/xorm"
	log2 "xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

func InitDB() *xorm.Engine {
	mysql := global.Config.MySQL
	engine, err := xorm.NewEngine(mysql.Category, mysql.ToString())
	if err != nil {
		log.Fatalf("连接数据库【%s:%s/%s】失败, 失败的原因：【%s】",
			mysql.Ip,
			mysql.Part,
			mysql.DataBase,
			err)
		os.Exit(0)
		return nil
	}
	err = engine.Ping()
	if err != nil {
		fmt.Printf("数据库连接错误:%v", err.Error())
		os.Exit(0)
		return nil
	}

	engine.SetLogger(logToFile())
	engine.ShowSQL(mysql.Print)
	engine.SetMaxIdleConns(mysql.MaxIdleConns)
	engine.SetMaxOpenConns(mysql.MaxOpenConns)
	engine.SetTableMapper(names.NewPrefixMapper(names.SnakeMapper{}, mysql.Prefix)) // 表前缀
	//engine.Sync2(new(models.CodeType))
	//engine.Sync2(new(models.CodeMiddle))
	//engine.Sync2(new(models.ArtCate))
	//engine.Sync2(new(models.User))
	//engine.Sync2(new(models.Article))
	//engine.Sync2(new(models.FileSync))
	//engine.Sync2(new(models.Comment))
	//engine.Sync2(new(models.Category))
	return engine
}

func logToFile() *log2.SimpleLogger {
	file, _ := os.OpenFile("./logs/sql.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	return log2.NewSimpleLogger(file)
}

// InitTable 数据表初始化控制
func InitTable(engine *xorm.Engine, beans ...interface{}) {
	// 判断config目录下面是否存在锁定文件
	file, err := os.Open("config/init.lock")
	defer file.Close()
	if err != nil && os.IsNotExist(err) {
		if err := engine.Sync2(beans); err != nil {
			log.Println("创建数据表失败", err.Error())
			return
		}

		file, err := os.Create("config/init.lock")
		if err != nil {
			return
		}
		defer file.Close()
		file.Write([]byte(time.Now().String()))
	} else {
		log.Println("数据表已经初始化无需再次初始化")
		return
	}
}
